package org.beikbank.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * http://localhost:8080/login
 */
@Controller
public class LoginController {


	@RequestMapping("/")
	public String index(){
		return "index";
	}

	@RequestMapping("/adminRole")
	@RequiresRoles("admin")
	@ResponseBody
	public String adminStr(){
		return "角色adminStr";
	}

	@RequestMapping("/userCreate")
	@RequiresPermissions("user:create")
	@ResponseBody
	public String userCreate(){
		return "权限userCreate";
	}

	@RequestMapping(value="/login",method = RequestMethod.GET)
	public String login(){
        return "login";
	}

    @RequestMapping(value="/remove",method = RequestMethod.GET)
    @ResponseBody
    public String remove(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "remove登出了";
    }

	
	@RequestMapping(value="/login",method = RequestMethod.POST)
	public String doLogin(String username,String password,Model model){
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		String emsg="";

		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			emsg="用户名不存在";
		}catch (IncorrectCredentialsException e) {
			emsg="密码错误";
		}catch (LockedAccountException e) {
			emsg="账号被锁定";
		}catch (AuthenticationException e) {
			emsg="错误："+e.getMessage();
		}
		
		if(!StringUtils.hasText(emsg)){
			return "redirect:/";
		}
		
		model.addAttribute("emsg", emsg);
		
		return "login";
	}
	
}
